package cn.gov.anhai.controller;

import cn.gov.anhai.filter.Auth;
import cn.gov.anhai.service.DynamicService;
import cn.gov.anhai.service.TourismService;
import cn.gov.anhai.service.UserService;
import cn.gov.anhai.utils.ApiResult;
import cn.gov.anhai.utils.LoginUtil;
import cn.gov.anhai.utils.MyUtil;
import cn.gov.anhai.utils.WeiXinUtil;
import cn.gov.anhai.vo.LoginRequestBody;
import cn.gov.anhai.vo.UserInfo;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"用户"})
public class UserController {
    private Logger logger = LoggerFactory.getLogger(TourismController.class);

    @Resource
    WeiXinUtil wxUtil;

    @Resource
    UserService userService;

    @Resource
    DynamicService dynamicService;

    @Resource
    TourismService tourismService;


    // 服务端接口示例代码（Java）
    @PostMapping("/HuaWeiLogin")
    public ApiResult<Object> HuaWeiLogin(@RequestBody JSONObject object, HttpServletRequest request) throws IOException {
        LoginRequestBody objects = new LoginRequestBody();
        objects.setAuthCode(object.getString("authCode"));
        objects.setNickName(object.getString("quickLoginAnonymousNickName"));
        objects.setAvatarUrl(object.getString("quickLoginAnonymousAvatarUri"));
        return userService.loginWithHuawei(objects);
    }

    /**
     * 登录
     */
    @PostMapping(value = "/login")
    @ApiOperation(value = "登录")
    public ApiResult<Object> login(@RequestBody JSONObject object, HttpServletRequest request) throws Exception {
        String xcxCode = object.getString("xcxCode");
        String phoneCode = object.getString("phoneCode");

        return userService.loginByWeiXinPhone(xcxCode, phoneCode);
    }

    /**
     * 登录
     */
    @PostMapping(value = "/login/phone")
    @ApiOperation(value = "手机登录")
    public ApiResult<Object> loginByPhone(@RequestBody JSONObject object, HttpServletRequest request) throws Exception {
        String phone = object.getString("phone");
        String password = object.getString("password");

        return userService.loginByPhoneAndPassword(phone, password);
    }

    /**
     * 手机注册
     */
    @PostMapping(value = "/register")
    @ApiOperation(value = "手机注册")
    public ApiResult<Object> register(@RequestBody JSONObject object, HttpServletRequest request) throws Exception {
        String phone = object.getString("phone");
        String password = object.getString("password");

        return userService.register(phone, password);
    }

    /**
     * 获取用户信息
     */
    @Auth
    @GetMapping(value = "/user/info")
    @ApiOperation(value = "获取用户信息")
    public ApiResult<Object> info(HttpServletRequest request) throws Exception {
        Map<String, Object> info = userService.info(LoginUtil.getToken(request));
        if (info == null) return ApiResult.fail("未登录或已登出，请重新登录");
        return ApiResult.ok(info);
    }

    /**
     * 修改昵称
     */
    @Auth
    @PutMapping(value = "/user/nickname")
    @ApiOperation(value = "修改昵称")
    public ApiResult<Object> updateName(@RequestBody JSONObject object, HttpServletRequest request) throws Exception {
        String nickname = object.getString("nickname");
        return userService.updateName(LoginUtil.getToken(request), nickname);
    }

    /**
     * 修改头像
     */
    @Auth
    @PutMapping(value = "/user/avatar")
    @ApiOperation(value = "修改头像")
    public ApiResult<Object> updateAvatar(@RequestBody JSONObject object, HttpServletRequest request) throws Exception {
        Long avatar = object.getLong("ossId");
        //System.out.println("avatar=" + avatar);
        return userService.updateAvatar(LoginUtil.getToken(request), avatar);
    }

    /**
     * 我的动态
     */
    @Auth
    @GetMapping(value = "/mine/dynamic/list")
    @ApiOperation(value = "我的动态")
    public ApiResult<Object> dynamicList(Integer current, Integer size, Integer status, String sort, HttpServletRequest request) throws Exception {
        Long userID = LoginUtil.getToken(request);
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> records = dynamicService.list(current, size, null, userID, null, null, status, sort);
        Integer total = dynamicService.listCount(null, userID, null, null, status);
        result.put("records", records);
        result.put("total", total);
        return ApiResult.ok(result);
    }

    /**
     * 获得的赞
     */
    @Auth
    @GetMapping(value = "/mine/like/list")
    @ApiOperation(value = "获得的赞")
    public ApiResult<Object> getLikeList(Integer current, Integer size, HttpServletRequest request) throws Exception {
        Long userID = LoginUtil.getToken(request);
        List<Map<String, Object>> records = userService.dynamicList(current, size, userID, 1);
        Integer total = userService.dynamicListCount(userID, 1);

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        return ApiResult.ok(result);
    }

    /**
     * 获得的收藏
     */
    @Auth
    @GetMapping(value = "/mine/collect/list")
    @ApiOperation(value = "获得的收藏")
    public ApiResult<Object> getCollectList(Integer current, Integer size, HttpServletRequest request) throws Exception {
        Long userID = LoginUtil.getToken(request);
        List<Map<String, Object>> records = userService.dynamicList(current, size, userID, 2);
        Integer total = userService.dynamicListCount(userID, 2);

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        return ApiResult.ok(result);
    }

    /**
     * 收藏的打卡点
     */
    @Auth
    @GetMapping(value = "/mine/collect/tourism/list")
    @ApiOperation(value = "收藏的打卡点")
    public ApiResult<Object> getCollectTourismList(Integer current, Integer size, HttpServletRequest request) throws Exception {
        Long userID = LoginUtil.getToken(request);
        List<Map<String, Object>> records = tourismService.list(current, size, null, null, userID, null, null);
        Integer total = tourismService.listCount(null, null, userID, null, null);

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        return ApiResult.ok(result);
    }

    /**
     * 收藏的动态
     */
    @Auth
    @GetMapping(value = "/mine/collect/dynamic/list")
    @ApiOperation(value = "收藏的动态")
    public ApiResult<Object> getCollectDynamicList(Integer current, Integer size, HttpServletRequest request) throws Exception {
        Long userID = LoginUtil.getToken(request);
        List<Map<String, Object>> records = dynamicService.list(current, size, null, null, userID, 0, 2, "desc");
        Integer total = dynamicService.listCount(null, null, userID, 0, 2);

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        return ApiResult.ok(result);
    }

    /**
     * 旅游打卡榜
     */
    @GetMapping(value = "/travel/punch/list")
    @ApiOperation(value = "旅游打卡榜")
    public ApiResult<Object> getTravelPunchList(Integer current, Integer size, Long type, String time, HttpServletRequest request) throws Exception {
        if (time == null) time = MyUtil.getNow("yyyy-MM");
        String[] times = time.split("\\-");
        int year = Integer.parseInt(times[0]);
        int month = Integer.parseInt(times[1]);

        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        String start = sdf.format(cal.getTime()) + " 00:00:00";

        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        String end = sdf.format(cal.getTime()) + " 23:59:59";

        System.out.println("start=" + start + "====" + "end=" + end);

        List<Map<String, Object>> records = tourismService.list(current, size, type, null, null, start, end);
        Integer total = tourismService.listCount(type, null, null, start, end);

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        return ApiResult.ok(result);
    }

    /**
     * 客服电话
     */
    @GetMapping(value = "/mine/service/phone")
    @ApiOperation(value = "客服电话")
    public ApiResult<Object> getServicePhone(HttpServletRequest request) throws Exception {
        String phone = userService.getServicePhone();
        return ApiResult.ok("客服电话", phone);
    }
}
